/*
* Copyright (C) 2010 Mamadou Diop.
*
* Contact: Mamadou Diop <diopmamadou(at)doubango.org>
*	
* This file is part of imsdroid Project (http://code.google.com/p/imsdroid)
*
* imsdroid is free software: you can redistribute it and/or modify it under the terms of 
* the GNU General Public License as published by the Free Software Foundation, either version 3 
* of the License, or (at your option) any later version.
*	
* imsdroid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
* See the GNU General Public License for more details.
*	
* You should have received a copy of the GNU General Public License along 
* with this program; if not, write to the Free Software Foundation, Inc., 
* 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
*/
package com.logicwin.RobotTravel.Services.Impl;

import com.logicwin.RobotTravel.Services.IScreenService;
import com.logicwin.RobotTravel.Services.IPositionService;
import com.logicwin.RobotTravel.Services.Impl.ServiceManager;

import com.logicwin.RobotTravel.RobotTravel;
import com.logicwin.RobotTravel.Main;
import com.logicwin.RobotTravel.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;

/**
 * Screen Manager. Entry point to retrieve all services (Singletons).
 * 
 * @author root
 * 
 */
public class ServiceManager  extends Service 
{	
	/* Singletons */

	private static final ScreenService screenService = new ScreenService();
	private static final PositionService positionService = new PositionService();
	
	private static final String TAG = ServiceManager.class.getCanonicalName();
	private static final String CONTENT_TITLE = "IMSDroid";
	
	private static Vibrator vibrator;
	
	private static boolean started;
	private static Main mainActivity;
	private static NotificationManager notifManager;
	private static final int NOTIF_REGISTRATION_ID = 19833891;
	private static final int NOTIF_AVCALL_ID = 19833892;
	private static final int NOTIF_SMS_ID = 19833893;
	private static final int NOTIF_CONTSHARE_ID = 19833894;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		if(ServiceManager.notifManager == null){
			ServiceManager.notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		}
		
		// Display a notification about us starting.  We put an icon in the status bar.
		ServiceManager.showRegistartionNotif(R.drawable.bullet_ball_glass_red_16, "You are not connected");
		
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		
		Bundle bundle = intent.getExtras();
		if(bundle != null && bundle.getBoolean("autostarted")){
			ServiceManager.start();
		}
		
		/* autostarts next time, unless user explicitly exited */
		SharedPreferences settings = getSharedPreferences(Main.class.getCanonicalName(), 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("autostarts", true);
		editor.commit();
	}	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		// Cancel the persistent notifications.
		ServiceManager.notifManager.cancel(ServiceManager.NOTIF_REGISTRATION_ID);
		ServiceManager.notifManager.cancel(ServiceManager.NOTIF_AVCALL_ID);
		
        // Tell the user we stopped.
        //Toast.makeText(this, "imsdroid shutting down...", Toast.LENGTH_SHORT).show();
	}
	
    private static void showNotification(int notifId, int drawableId, String tickerText) {
        // Set the icon, scrolling text and timestamp
        final Notification notification = new Notification(drawableId, "", System.currentTimeMillis());
        
        Intent intent = new Intent(RobotTravel.getContext(), Main.class);
    	intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP  | Intent.FLAG_ACTIVITY_NEW_TASK);
        
        switch(notifId){
        	case NOTIF_REGISTRATION_ID:
        		//notification.ledARGB = 0xff00ff00;
        		//notification.ledOnMS = 300;
        		//notification.ledOffMS = 1000;
        		notification.flags |= Notification.FLAG_ONGOING_EVENT /*| Notification.FLAG_SHOW_LIGHTS*/;
        		//notification.defaults |= Notification.DEFAULT_SOUND;
        		intent.putExtra("notif-type", "reg");
        		/* Main activity already onTop -> do not pass the screen Id */
        		break;
        	case NOTIF_SMS_ID:
        		notification.flags |= Notification.FLAG_AUTO_CANCEL;
        		intent.putExtra("action", Main.ACTION_SHOW_HISTORY);
        		break;
        	case NOTIF_CONTSHARE_ID:
        		//notification.flags |= Notification.FLAG_AUTO_CANCEL;
        		intent.putExtra("action", Main.ACTION_SHOW_CONTSHARE_SCREEN);
        		break;
       		default:
       			
       			break;
        }
        
        PendingIntent contentIntent = PendingIntent.getActivity(RobotTravel.getContext(), notifId/*requestCode*/, intent, PendingIntent.FLAG_UPDATE_CURRENT);     

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(RobotTravel.getContext(), ServiceManager.CONTENT_TITLE, tickerText, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        ServiceManager.notifManager.notify(notifId, notification);
    }
    
    public static void showRegistartionNotif(int drawableId, String tickerText){
    	Log.d(ServiceManager.TAG, "showRegistartionNotif");
    	ServiceManager.showNotification(NOTIF_REGISTRATION_ID, drawableId, tickerText);
    }
    
    public static void showAVCallNotif(int drawableId, String tickerText){
    	ServiceManager.showNotification(NOTIF_AVCALL_ID, drawableId, tickerText);
    }
    
    public static void showSMSNotif(int drawableId, String tickerText){
    	ServiceManager.showNotification(NOTIF_SMS_ID, drawableId, tickerText);
    }
    
    public static void showContShareNotif(int drawableId, String tickerText){
    	ServiceManager.showNotification(NOTIF_CONTSHARE_ID, drawableId, tickerText);
    }
    
    public static void cancelAVCallNotif(){
    	ServiceManager.notifManager.cancel(ServiceManager.NOTIF_AVCALL_ID);
    }
    
    public static void cancelContShareNotif(){
    	ServiceManager.notifManager.cancel(ServiceManager.NOTIF_CONTSHARE_ID);
    }
    
	public static void setMainActivity(Main mainActivity){
		ServiceManager.mainActivity = mainActivity;
	}
	
	public static Main getMainActivity(){
		return ServiceManager.mainActivity;
	}
	
	/**
	 * Starts all services
	 * 
	 * @return true if succeed and false otherwise
	 */
	public static boolean start() {
		if(ServiceManager.started){
			return true;
		}
		
		// Start Android service
		RobotTravel.getContext().startService(
				new Intent(RobotTravel.getContext(), ServiceManager.class));
		
		boolean success = true;

		if(!success){
			Log.e(ServiceManager.TAG, "Failed to start services");
		}
		
		ServiceManager.started = true;
		return true;
	}

	/**
	 * Stops all services
	 * 
	 * @return true if succeed and false otherwise
	 */
	public static boolean stop() {
		if(!ServiceManager.started){
			return true;
		}
		
		// stops Android service
		RobotTravel.getContext().stopService(
				new Intent(RobotTravel.getContext(), ServiceManager.class));
		
		boolean success = true;

		ServiceManager.notifManager.cancel(ServiceManager.NOTIF_REGISTRATION_ID);
		ServiceManager.notifManager.cancel(ServiceManager.NOTIF_AVCALL_ID);
		
		if(!success){
			Log.e(ServiceManager.TAG, "Failed to stop services");
		}
		
		ServiceManager.started = false;
		return success;
	}
	
	public static void vibrate(long milliseconds){
		if(ServiceManager.vibrator == null){
			ServiceManager.vibrator = (Vibrator)RobotTravel.getContext().getSystemService(Context.VIBRATOR_SERVICE);
		}
		ServiceManager.vibrator.vibrate(milliseconds);
	}
	/**
	 * Gets the Screen Service.
	 * 
	 * @return
	 */
	public static IScreenService getScreenService() {
		return (IScreenService) ServiceManager.screenService;
	}	
	public static IPositionService getPositoinService(){
		return (IPositionService) positionService;
	}
}
